package com.example.apiproject.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.apiproject.exception.apiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    private final String uploadFilePath = System.getProperty("user.dir") + "/file/";
//文件上传
    @RequestMapping("/upload")
    public String httpUpload(@RequestParam("files") MultipartFile files[]){
        if (files.length==0) {
            throw new apiException("上传文件不能为空");
        }
        JSONObject object=new JSONObject();
        String flag = System.currentTimeMillis()+"";
        if(!FileUtil.isDirectory(uploadFilePath)) {
            FileUtil.mkdir(uploadFilePath);
        }


        for(int i=0;i<files.length;i++){
            String fileName = files[i].getOriginalFilename();  // 文件名

            File dest = new File(uploadFilePath+flag+fileName);


            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                files[i].transferTo(dest);

            } catch (Exception e) {
                log.error("{}",e);
                object.put("success" , 0 );
                object.put("result","程序错误，请重新上传");
                return object.toString();
            }
        }
        object.put("success",1);
        object.put("result","文件上传成功");
        object.put("url",flag);
        return object.toString();
    }
//单文件下载
    @RequestMapping("/download")
    public String fileDownLoad(HttpServletResponse response, @RequestParam("flag") String flag){
        List<String> filenames = FileUtil.listFileNames(uploadFilePath);
        String fileName = filenames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        File file = new File( uploadFilePath+'/'+ fileName);
        if(!file.exists()){
            return "下载文件不存在";
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName );

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            log.error("{}",e);
            return "下载失败";
        }
        return "下载成功";
    }
//    文件批量下载
    @GetMapping("/downloadlist")
    public void downLoadList(  HttpServletResponse response ,@RequestParam("flag") String flag) throws UnsupportedEncodingException {
        List<String> filenames = FileUtil.listFileNames(uploadFilePath);
        List<String> pathList = filenames.stream().filter(name -> name.contains(flag)).collect(Collectors.toList());

        response.reset();
        response.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(flag+".zip", "UTF-8"));
        response.setCharacterEncoding("utf-8");

        response.setContentType("application/octet-stream");

        try(ZipOutputStream zipOutputStream=new ZipOutputStream(new BufferedOutputStream(response.getOutputStream())))
        {
            for(String pathName:pathList)
            {
                File file =new File(uploadFilePath+pathName);
                String fileName=file.getName();
                zipOutputStream.putNextEntry(new ZipEntry(fileName));
                try(BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file))){
                    byte[] bytes = new byte[1024];
                    int i=0;
                    while((i=bis.read(bytes))!=-1)
                    {
                        zipOutputStream.write(bytes,0,i);
                    }
                    zipOutputStream.closeEntry();
                }catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}